import axios from 'axios'
import store from '@/store'
import router from '@/router'

// 创建了一个新的axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API
        // baseURL: '/api'
})

// axios的请求拦截器
service.interceptors.request.use(function(config) {
    const token = store.state.user.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, function(error) {
    return Promise.reject(error)
})

// axios的响应拦截器
service.interceptors.response.use(function(response) {
    if (!response.data.success) {
        return Promise.reject.apply(response.data.message)
    }
    return response.data
}, function(error) {
    // 判断是否是401的错误
    if (error.response.statue === 401 || error.response.data.code === 10002) {
        store.dispatch('uer/logout')
        router.push('/login?url=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    return Promise.reject(error)
})

// 导出axios实例
export default service